package com.lyj.linearalgebra.admin.web.servlet;

import cn.itcast.commons.CommonUtils;
import cn.itcast.servlet.BaseServlet;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lyj.linearalgebra.admin.domain.Admin;
import com.lyj.linearalgebra.admin.service.AdminException;
import com.lyj.linearalgebra.admin.service.AdminService;
import com.lyj.linearalgebra.post.service.PostService;
import com.lyj.linearalgebra.user.dao.UserDao;
import com.lyj.linearalgebra.user.domain.User;
import com.lyj.linearalgebra.user.service.UserException;

/**
 * Servlet implementation class AdminServlet
 */
@WebServlet("/AdminServlet")
public class AdminServlet extends BaseServlet {

	private AdminService adminService = new AdminService();
	private PostService postService = new PostService();

	public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Admin form = CommonUtils.toBean(request.getParameterMap(), Admin.class);
		/*
		 * 输入校验 1. 创建一个Map，用来封装错误信息，其中key为表单字段名称，值为错误信息
		 */
		Map<String, String> errors = new HashMap<String, String>();
		/*
		 * 2. 获取form中的username、password、email进行校验
		 */
		String username = form.getUsername();
		if (username == null || username.trim().isEmpty()) {
			errors.put("username", "用户名不能为空！");
		} else if (username.length() < 3 || username.length() > 10) {
			errors.put("username", "用户名长度必须在3~10之间！");
		}

		String password = form.getPassword();
		if (password == null || password.trim().isEmpty()) {
			errors.put("password", "密码不能为空！");
		} else if (password.length() < 3 || password.length() > 10) {
			errors.put("password", "密码长度必须在3~10之间！");
		}

		if (errors.size() > 0) {
			// 1. 保存错误信息
			// 2. 保存表单数据
			// 3. 转发到regist.jsp
			request.setAttribute("errors", errors);
			request.setAttribute("form", form);
			return "f:/adminLogin.jsp";
		}
		try {
			Admin admin = adminService.login(form);
			request.getSession().setAttribute("session_admin", admin);
			return "r:/admin.jsp";
		} catch (AdminException e) {
			request.setAttribute("msg", e.getMessage());
			request.setAttribute("form", form);
			return "f:/adminLogin.jsp";
		}

	}

	public String exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Admin admin = (Admin) request.getSession().getAttribute("session_admin");
		if (admin == null) {
			request.setAttribute("msg", "您还没有登录，不能退出！");
		} else {
			request.getSession().removeAttribute("session_admin");
			request.setAttribute("msg", "您已退出！");
		}
		return "f:/msg.jsp";
	}

	public String reset(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Admin admin = (Admin) request.getSession().getAttribute("session_admin");
		String verifyCode = request.getParameter("verifyCode");
		String password = request.getParameter("password");
		String password1 = request.getParameter("password1");

		Map<String, String> errors = new HashMap<String, String>();

		String session_vcode = (String) request.getSession().getAttribute("session_vcode");
		if (password == null || password.trim().isEmpty()) {
			errors.put("password", "密码不能为空!");
		} else if (password1 == null || password1.trim().isEmpty()) {
			errors.put("password1", "密码不能为空!");
		} else if (!password.equals(password1)) {
			errors.put("password1", "密码不一致!");
		} else if (verifyCode == null || verifyCode.trim().isEmpty()) {
			errors.put("verifyCode", "验证码不能为空!");
		} else if (!verifyCode.equals(session_vcode)) {
			System.out.println(session_vcode);
			errors.put("verifyCode", "验证码错误!");
		}

		if (errors.size() > 0) {
			request.setAttribute("password", password);
			request.setAttribute("password1", password1);
			request.setAttribute("verifyCode", verifyCode);
			request.setAttribute("errors", errors);
			return "f:/resetPwd_admin.jsp";
		}
		adminService.reset(admin.getAid(), password);
		request.setAttribute("msg", "密码更改成功,请重新登录！");
		return "f:/msg.jsp";
	}

	public String resetInfo(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		Map<String, String> form = new HashMap<String, String>();
		Map<String, String> errors = new HashMap<String, String>();

		String username = request.getParameter("username");
		String email = request.getParameter("email");

		Admin admin = (Admin) request.getSession().getAttribute("session_admin");
		form.put("username", username);
		form.put("email", email);

		if (email != null && !email.trim().isEmpty()) {
			if (!email.matches("\\w+@\\w+\\.\\w+")) {
				errors.put("email", "Email格式错误！");
			}
		} else if (username == null || username.trim().isEmpty()) {
			errors.put("error", "未输入信息！");
		}

		if (errors.size() > 0) {
			request.setAttribute("errors", errors);
			request.setAttribute("form", form);
			return "f:/info_admin.jsp";
		}

		try {
			adminService.resetInfo(admin, form);
			request.setAttribute("msg", "修改成功，请重新登录!");
			return "f:/msg.jsp";
		} catch (AdminException e) {
			request.setAttribute("msg", e.getMessage());
			request.setAttribute("errors", errors);
			request.setAttribute("form", form);
			return "f:/info_admin.jsp";

		}

	}

	public String allQuestions(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setAttribute("postList", postService.findAll());
		return "f:/interrogation_admin.jsp";
	}

	public String manageUsers(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		Admin admin = (Admin) request.getSession().getAttribute("session_admin");
		if (admin != null) {
			request.setAttribute("users", adminService.findAllUsers());
			return "f:/manageUsers.jsp";
		} else {
			return "f:/manageUsers.jsp";
		}
	}

	public String deleteUser(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		Admin admin = (Admin) request.getSession().getAttribute("session_admin");
		if (admin != null) {
			String uid = request.getParameter("uid");
			adminService.deleteUser(uid);
			return manageUsers(request, response);
		}else {
			return "f:/manageUsers.jsp";
		}
	}

	public String managePosts(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		Admin admin = (Admin) request.getSession().getAttribute("session_admin");
		if (admin != null) {
			request.setAttribute("posts", adminService.getAllPosts());
			return "f:/managePosts.jsp";
		}else {
			return "f:/managePosts.jsp";
		}
	}

	
	public String deletePost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Admin admin = (Admin) request.getSession().getAttribute("session_admin");
		if (admin != null) {
			String pid = request.getParameter("pid");
			adminService.deletePost(pid);
			return managePosts(request, response);
		}else {
			return managePosts(request, response); 
		}
	}

	public String addManager(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		Admin form = CommonUtils.toBean(request.getParameterMap(), Admin.class);
		form.setAid(CommonUtils.uuid());
		/*
		 * 输入校验
		 * 1. 创建一个Map，用来封装错误信息，其中key为表单字段名称，值为错误信息
		 */
		Map<String,String> errors = new HashMap<String,String>();
		/*
		 * 2. 获取form中的username、password、email进行校验
		 */
		String username = form.getUsername();
		if(username == null || username.trim().isEmpty()) {
			errors.put("username", "用户名不能为空！");
		} else if(username.length() < 3 || username.length() > 10) {
			errors.put("username", "用户名长度必须在3~10之间！");
		}
		
		String password = form.getPassword();
		if(password == null || password.trim().isEmpty()) {
			errors.put("password", "密码不能为空！");
		} else if(password.length() < 3 || password.length() > 10) {
			errors.put("password", "密码长度必须在3~10之间！");
		}
		
		String password1 = request.getParameter("password1");
		if(password1 == null || password1.trim().isEmpty()) {
			errors.put("password1", "密码不能为空！");
		} else if(!password1.equals(password)) {
			errors.put("password1", "两次密码不一致!");
		}
		
		String email = form.getEmail();
		if(email == null || email.trim().isEmpty()) {
			errors.put("email", "Email不能为空！");
		} else if(!email.matches("\\w+@\\w+\\.\\w+")) {
			errors.put("email", "Email格式错误！");
		}
		/*
		 * 3. 判断是否存在错误信息
		 */
		if(errors.size() > 0) {
			// 1. 保存错误信息
			// 2. 保存表单数据
			// 3. 转发到regist.jsp
			request.setAttribute("password1", password1);
			request.setAttribute("errors", errors);
			request.setAttribute("form", form);
			return "f:/addManager.jsp";
		}
		
		/*
		 * 调用service的regist()方法
		 */
		try {
			adminService.addManager(form);
		} catch (AdminException e) {
			/*
			 * 1. 保存异常信息
			 * 2. 保存form
			 * 3. 转发到regist.jsp
			 */
			request.setAttribute("password1", password1);
			request.setAttribute("msg", e.getMessage());
			request.setAttribute("form", form);
			return "f:/addManager.jsp";
		}		
		
		request.setAttribute("msg", "添加成功!");
		return "f:/addManager.jsp";
	}

}
